import { Globals } from "./Global";
import { log_debug } from "./Utils";
import MapLayer from "./MapLayer";
import AudioMgr from "./AudioMgr";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Prop extends cc.Component {

    @property(cc.SpriteFrame)
    frames: cc.SpriteFrame[] = [];

    mapLayer: MapLayer;
    effectIndex: number;

    init() {
        this.mapLayer = cc.find("/Canvas/GameLayer/MapLayer").getComponent(MapLayer);
        
        // 随机道具
        let choice = Math.ceil(Math.random() * 5);
        this.effectIndex = choice;
        this.getComponent(cc.Sprite).spriteFrame = this.frames[this.effectIndex];

        // 随机位置
        let random_x = Math.random() * Globals.MAP_HEIGHT;
        let random_y = Math.random() * Globals.MAP_WIDTH;
        this.node.setPosition(cc.v2(random_x, random_y));

        // 闪烁动画
        cc.find("/Game/AudioMgr").getComponent(AudioMgr).playAudio("prop_out", false);
        this.node.runAction(cc.blink(1, 5));

        // 20s后消失
        this.scheduleOnce(() => {
            this.onPropDestroyed();
        }, Globals.PROP_TIME);
    }

    onPropDestroyed() {
        this.unscheduleAllCallbacks();
        this.mapLayer.destroyProp(this.node);
    }

    takeEffect() {
        switch (this.effectIndex) {
            case 0:
                this.effect0();
                break;
            case 1:
                this.effect1();
                break;
            case 2:
                this.effect2();
                break;
            case 3:
                this.effect3();
                break;
            case 4:
                this.effect4();
                break;
            case 5:
                this.effect5();
                break;
            default:
                break;
        }
        this.onPropDestroyed();
    }

    // 生命+1
    effect0() {
        cc.find("/Game/AudioMgr").getComponent(AudioMgr).playAudio("add_life", false);
        this.mapLayer.propPlayerAddLife();
    }

    // level+1
    effect1() {
        cc.find("/Game/AudioMgr").getComponent(AudioMgr).playAudio("bouns", false);
        this.mapLayer.propPlayerAddLevel();
    }

    // 暂停敌方坦克
    effect2() {
        cc.find("/Game/AudioMgr").getComponent(AudioMgr).playAudio("stop_enemy", false);
        this.mapLayer.propStopEnemyTank();
    }

    // 清空敌方坦克
    effect3() {
        cc.find("/Game/AudioMgr").getComponent(AudioMgr).playAudio("tank_bomb", false);
        this.mapLayer.propClearEnemyTank();
    }

    // 加固基地
    effect4() {
        cc.find("/Game/AudioMgr").getComponent(AudioMgr).playAudio("reinforce", false);
        this.mapLayer.propReinoforce();
    }

    // 无敌buff
    effect5() {
        cc.find("/Game/AudioMgr").getComponent(AudioMgr).playAudio("invincible", false);
        this.mapLayer.propPlayerInvicible();
    }
}
